package com.say.framework.core.exception;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.FieldError;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import com.say.framework.core.security.exception.CommonException;
import com.say.framework.core.security.exception.RequestsException;
import com.say.framework.core.security.exception.TokenException;
import com.say.framework.core.util.ResponseConstant;
import com.say.framework.core.util.ResponseEntity;
import com.say.framework.core.util.StringUtil;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 
 * 类名称：ExceptionAdvice<br>
 * 类描述：异常处理<br>
 * @version v1.0
 *
 */
@ControllerAdvice
@ResponseBody
public class ExceptionAdvice {

    private static final Logger logger = LoggerFactory.getLogger("exceptionAdvice");

    /**
     * 400 - Bad Request
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(HttpMessageNotReadableException.class)
    public ResponseEntity handleHttpMessageNotReadableException(HttpMessageNotReadableException e) {
        logger.error("参数解析失败", e);
        return new ResponseEntity().failure(ResponseConstant.CODE_000, "无法解析JSON");
    }
    @ResponseStatus(HttpStatus.EXPECTATION_FAILED)
    @ExceptionHandler(RequestsException.class)
    public ResponseEntity handleRequestsException(RequestsException e) {
    	logger.error("请求太频繁，稍后再试", e);
    	return new ResponseEntity().failure(ResponseConstant.CODE_503, "请求太频繁，稍后再试");
    }
    
    /**
     * 401 - Unauthorized Request
     */
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    @ExceptionHandler(TokenException.class)
    public ResponseEntity handleTokenException(TokenException e) {
        ResponseEntity responseEntity = new ResponseEntity();
        String message = e.getMessage();
        Map<String, Object> data = null;
        if (StringUtil.isNotBlank(message)) {
            //失效的token
            int startIndex = message.indexOf("{");
            int endIndex = message.indexOf("}");
            if (startIndex > -1 && endIndex > -1) {
                String type = message.substring(startIndex + 1, endIndex);
                data = new HashMap<>(16);
                //告诉前端失效的原因：（1：被管理员强制下线，2：被其他超级管理员挤下线）
                data.put("type", type);
            }
        }
        logger.error("登录信息失效，请重新登录", e);
        return responseEntity.failure(ResponseConstant.CODE_401, "登录信息失效，请重新登录", data);
    }

    /**
     * 405 - Method Not Allowed
     */
    @ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED)
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public ResponseEntity handleHttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e) {
        logger.error("不支持当前请求方法", e);
        return new ResponseEntity().failure(ResponseConstant.CODE_000, "不支持当前请求方法");
    }

    /**
     * 415 - Unsupported Media Type
     */
    @ResponseStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE)
    @ExceptionHandler(HttpMediaTypeNotSupportedException.class)
    public ResponseEntity handleHttpMediaTypeNotSupportedException(Exception e) {
        logger.error("不支持当前媒体类型", e);
        return new ResponseEntity().failure(ResponseConstant.CODE_000, "不支持的内容类型");
    }

    /**
     * 500 - Internal Server Error
     */
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(Exception.class)
    public ResponseEntity handleException(Exception e) {
        logger.error("服务运行异常", e);
        return new ResponseEntity().failure(ResponseConstant.CODE_000, "服务运行异常:" + e.getMessage());
    }

    /**
     * 500 - Internal Server Error
     * 用于给用户提示时抛出，如：操作失败的原因
     */
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(CommonException.class)
    public ResponseEntity handleCommonException(CommonException e) {
        return new ResponseEntity().failure(ResponseConstant.CODE_000, e.getMessage());
    }

    /**
     * 500 - Internal Server Error
     * 参数校验失败时抛出，如：非空属性的值为空
     */
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        StringBuilder errorInfo = new StringBuilder();
        List<FieldError> fieldErrorList = e.getBindingResult().getFieldErrors();
        fieldErrorList.forEach(fieldError -> errorInfo.append(fieldError.getField()).append(" ").append(fieldError.getDefaultMessage()).append("，"));
        errorInfo.deleteCharAt(errorInfo.length() - 1);
        return new ResponseEntity().failure(ResponseConstant.CODE_000, errorInfo.toString());
    }
}
